package controllers

import (
	"cdam/enum"
	"cdam/models"
	"cdam/qiongqi"
	"cdam/util"
	"encoding/json"
	"errors"
	"github.com/astaxie/beego"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

// FlowProcessController operations for TFlowProcess
type FlowProcessController struct {
	beego.Controller
}

// URLMapping ...
func (c *FlowProcessController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
	c.Mapping("StartWorkflowInstance",c.StartProcess)
	c.Mapping("GotoNextTask",c.NextStep)
	c.Mapping("CreateProcess", c.CreateProcess)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("GetPublishFlowProcess",c.Getpublishflowprocess)
	c.Mapping("RecoverProcess",c.RecoverProcess)
	c.Mapping("GetTodoInstances",c.GetTodoInstances)
	c.Mapping("GetTodoInstancesNodes", c.GetTodoInstancesNodes)
}

type InstanceProcess struct {
	Id 					string                    	// 流程实例 ID
	Parameter 			interface{}        			// 参数
	FormId	  			string             			// 表单ID
	ProcessName 		string           			// 工作流程名称
	Code        		string           			// 工作流程代码
	CurrentParam   		string        				// 当前节点ID
	CurrentId      		string        				// 当前节点处理人 （下一步使用）
	CurrentHandler 		string        				// 当前节点处理人
	NextHandler  		string          			// 下一个节点处理人 （多人可以用逗号区分）
}

type InstanceNodeParameter struct {
	InstanceNodeId		int64						// 流程实例节点ID
	InstanceId			int64						// 流程实例ID
	CandidateId			int64						// 参与者ID
}

type InstanceToNextStepParameter struct {
	Id  				int64                       // 流程实例节点ID
	BtnClient			enum.BtnClientType			// 点击按钮的类型
	Parameters          interface{}					// 用户传入参数
}


// Delete ...
// @Title Delete
// @Description delete the FlowProcess
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /:id [delete]
func (c *FlowProcessController) Delete() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(idStr)
	if err := models.DeleteTFlowProcess(int64(id)); err == nil {
		c.Data["json"] = "OK"
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}

// StartWorkflowInstance ...
// @Title StartWorkflowInstance
// @Description startProcess
// @Param	body		body 	InstanceProcess	true		"body for InstanceProcess content"
// @Success 200 {object} models.FlowProcess
// @Failure 403 :id is empty
// @router /startProcess [post]
func (c *FlowProcessController) StartProcess() {
	var v = new(InstanceProcess)
	m := map[string]interface{}{}
	// 获取参数
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		m = c.StartProcesses(*v)
	}else{
		m["code"] = "80000"
		m["message"] = err.Error()
	}
	c.Data["json"] = m
	c.ServeJSON()
}

// GetTodoWorkflowInstance ...
// @Title 获取未完成工作流
// @Description get ToDoProcess by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.FlowProcess
// @Failure 403 :id is empty
// @router /GetTodoInstances [get]
func (c *FlowProcessController)GetTodoInstances()  {
	m := map[string]interface{}{}
	parameterProcess := qiongqi.QiongqiProcessParam{}
	instanceEngine := qiongqi.NewQiongqiProcess(parameterProcess)
	if instance,count,err := instanceEngine.FindTodoProcess(1,0,10); err == nil {
		m["code"] = "20000"
		m["data"] = instance
		m["count"] = count
	}else{
		m["code"] = "80000"
		m["message"] = err.Error()
	}
	c.Data["json"] = m
	c.ServeJSON()
}

func (c *FlowProcessController) StartProcesses(v InstanceProcess) map[string]interface{} {
	m := map[string]interface{}{}
	parameterProcess := qiongqi.QiongqiProcessParam{}
	// 流程代码
	parameterProcess.ProcessCode = v.Code
	// 实例名称
	parameterProcess.InstanceName = v.ProcessName
	// 当前任务节点输入参数
	parameterProcess.CurrentTaskParameters = v.Parameter
	// 当前任务参与人
	parameterProcess.CurrentTaskHandler = v.CurrentHandler
	// 下一个任务参与人
	parameterProcess.NextTaskHandler = v.NextHandler
	// 当前任务参与人输入参数
	parameterProcess.CurrentTaskInputParam = v.CurrentParam
	// 初始化引擎
	instanceEngine := qiongqi.NewQiongqiProcess(parameterProcess)

	if _,err := instanceEngine.StartWorkflowInstance(); err == nil {
		m["code"] = "20000"
	}else{
		m["code"] = "80000"
		m["message"] = err.Error()
	}
	return m
}

// GetTodoInstancesNodes ...
// @Title 获取未完成工作流
// @Description get ToDoProcess by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.FlowProcess
// @Failure 403 :id is empty
// @router /GetTodoInstancesNodes [get]
func (c *FlowProcessController)GetTodoInstancesNodes() {
	var v = new(InstanceNodeParameter)
	m := map[string]interface{}{}
	v.InstanceId,_  =  strconv.ParseInt(c.GetString("InstanceId"),10,64)
	v.InstanceNodeId,_  =  strconv.ParseInt(c.GetString("InstanceNodeId"),10,64)
	v.CandidateId,_  =  strconv.ParseInt(c.GetString("CandidateId"),10,64)
	parameterProcess := qiongqi.QiongqiProcessParam{}
	instanceEngine := qiongqi.NewQiongqiProcess(parameterProcess)
	if instance,err := instanceEngine.FindTodoProcessNodes(v.InstanceId,v.InstanceNodeId,v.CandidateId); err == nil {
		m["code"] = "20000"
		m["data"] = instance
	}else{
		m["code"] = "80000"
		m["message"] = err.Error()
	}
	c.Data["json"] = m
	c.ServeJSON()

}

// GotoNextTask ...
// @Title GotoNextTask
// @Description 进行下一步
// @Param	body		body 	InstanceProcess	true		"body for InstanceProcess content"
// @Success 200 {object} models.FlowProcess
// @Failure 403 :id is empty
// @router /nextStep [post]
func (c *FlowProcessController) NextStep() {
	var v = new(InstanceToNextStepParameter)
	m := map[string]interface{}{}
	// 获取参数
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {

		parameterProcess := qiongqi.QiongqiProcessParam{}
		parameterProcess.CurrentTaskHandler = "1"
		parameterProcess.NextTaskHandler = "100"
		parameterProcess.CurrentTaskInputParam = v.Parameters
		parameterProcess.CurrentTaskId = strconv.FormatInt(v.Id,10)
		parameterProcess.BtnClient  = v.BtnClient
		engine := qiongqi.NewQiongqiProcess(parameterProcess)
		if err = engine.GotoNextTask(); err == nil {
			m["code"] = "20000"
		}else{
			m["code"] = "80000"
			m["message"] = err.Error()
		}
	}else{
		m["code"] = "80000"
		m["message"] = err.Error()
	}
	c.Data["json"] = m
	c.ServeJSON()
}

// Create Process ...
// @Title Create Process
// @Description create Process
// @Param	body		body 	models.FlowProcess	true		"body for FlowProcess content"
// @Success 201 {int} models.FlowProcess
// @Failure 403 body is empty
// @router /CreateProcess [post]
func (c *FlowProcessController) CreateProcess() {
	var v models.FlowProcess
	m := map[string]interface{}{}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		v.Id = int64(int(rand.New(util.Seed).Int63n(100000000)))
		v.Status = 0
		v.Createdate = time.Now()
		v.Version = 1
		if _, err := models.AddTFlowProcess(&v); err == nil {
			c.Ctx.Output.SetStatus(201)
			m["code"] = "20000"
			// c.Data["json"] = v
		} else {
			m["code"] = "80000"
			m["message"] = err.Error()
			// c.Data["json"] = err.Error()
		}
	} else {
		m["code"] = "80000"
		m["message"] = err.Error()
	}
	c.Data["json"] = m
	c.ServeJSON()
}

// Post ...
// @Title Post
// @Description create FlowProcess
// @Param	body		body 	models.FlowProcess	true		"body for FlowProcess content"
// @Success 201 {int} models.FlowProcess
// @Failure 403 body is empty
// @router / [post]
func (c *FlowProcessController) Post() {
	// var v models.FlowProcess
	c.ServeJSON()
}


// GetOne ...
// @Title Get One
// @Description get FlowProcess by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.FlowProcess
// @Failure 403 :id is empty
// @router /:id [get]
func (c *FlowProcessController) GetOne() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(idStr)
	v, err := models.GetTFlowProcessById(int64(id))
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = v
	}
	c.ServeJSON()
}

// GetAll ...
// @Title Get All
// @Description get FlowProcess
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.FlowProcess
// @Failure 403
// @router / [get]
func (c *FlowProcessController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	var query = make(map[string]string)
	var limit int64 = 10
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	l, count, err := models.GetAllTFlowProcess(query, fields, sortby, order, offset, limit)
	m := map[string]interface{}{}
	if err != nil {
		m["code"] = "80000"
		m["message"] = err.Error()
	} else {
		m["code"] = "20000"
		m["data"] = l
		m["count"] = count
	}
	c.Data["json"] = m
	c.ServeJSON()
}

// RecoverProcess ...
// RecoverProcess ...
// @Title RecoverProcess
// @Description get FlowProcess by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.FlowProcess
// @Failure 403 :id is empty
// @router /recoverProcess/:id [get]
func (c *FlowProcessController) RecoverProcess()  {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(idStr)
	var m = make(map[string]interface{})
	err := models.RecoverOrHangupProcess(int64(id))
	if err == nil {
		m["code"] = "20000"
	} else {
		m["code"] = "80000"
		m["message"] = err.Error()
	}
	c.Data["json"] = m
	c.ServeJSON()
}

// Put ...
// @Title Put
// @Description update the FlowProcess
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.FlowProcess	true		"body for TFlowProcess content"
// @Success 200 {object} models.FlowProcess
// @Failure 403 :id is not int
// @router /:id [put]
func (c *FlowProcessController) Put() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(idStr)
	v := models.FlowProcess{Id: int64(id)}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		if err := models.UpdateTFlowProcessById(&v); err == nil {
			c.Data["json"] = "OK"
		} else {
			c.Data["json"] = err.Error()
		}
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}

// GetAllPublish ...
// @Title Get All
// @Description get FlowProcess
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.FlowProcess
// @Failure 403
// @router /publishflowprocess [get]
func (c *FlowProcessController) Getpublishflowprocess() {
	var fields []string
	var sortby []string
	var order []string
	var query = make(map[string]string)
	var limit int64 = 10
	var offset int64
	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	l, count, err := models.GetAllFlowProcessList(query, fields, sortby, order, offset, limit)
	m := map[string]interface{}{}
	if err != nil {
		m["code"] = "80000"
		m["message"] = err.Error()
	} else {
		m["code"] = "20000"
		m["data"] = l
		m["count"] = count
	}
	c.Data["json"] = m
	c.ServeJSON()
}



